package com.atjava.nebula.core.exception.baseExp;

import java.text.MessageFormat;

import com.atjava.nebula.core.exception.bean.ExceptionInfo;
import com.atjava.nebula.core.exception.config.ExpMsgResoureConfig;
import com.atjava.nebula.core.exception.support.ExceptionUtil;
import com.atjava.nebula.core.exception.support.ExpHandlerFactory;

/**
 * 所有checked异常的基类
 */
/**
 * @author kyo
 *
 */
public class BaseAppException extends Exception {

	private static final long serialVersionUID = -5829545098534135052L;

	protected String exceptionMessage; 	//异常信息    
    
    protected String context ;			//msgCode是否有上下文
    protected String msgCode ;			//异常信息代码
    protected Object[] args ;			//传入异常信息的参数

    /**
     * 简单传入异常信息的构造器
     * */
	public BaseAppException(String message) {
		super(message) ;
		exceptionMessage = message ;
    }
	
	public BaseAppException(Throwable th, String message) {
		super(message,th) ;
		
		exceptionMessage = message ;
	}

	public BaseAppException(String msgCode, Object[] args, String context) {
    	this.msgCode = msgCode ;
    	this.args = args ;
    	this.context = context ;
    } 

    public String toString() {
        String s = getClass().getName();
        return s + ": " + exceptionMessage;
    }

    /*
     * 得到异常的友好信息
     */
    public String getMessage() {
    	//在调用BaseAppException(str)构造器时
    	if(exceptionMessage != null) {
    		return exceptionMessage ;
    	}
    	
    	//如果msgCode为空,根据当前异常类名得到msgCode
    	if(msgCode == null) {
    		ExceptionInfo info = ExceptionUtil.getExceptionInfo(this) ;
    		if(info == null) {
    			return null ;
    		}
    		String _msgCode = info.getMessageCode() ;
    		msgCode = ExpMsgResoureConfig.getInstance().getMessage(_msgCode, context) ;
    	}
    	//根据msgCode和args得到一个友好的信息,如果它们不匹配,会出错吗?
    	exceptionMessage = MessageFormat.format(msgCode, args) ;
        return exceptionMessage;
    }
    
    //重写printStackTrace()方法,打印自定义的异常信息
    public void printStackTrace() {
		ExpHandlerFactory.getInstance().handleException(this) ;		
	}  
    
    
    /**发生异常时跳转的URL
     * @return URL
     */
    public String getForwardURL() {
    	ExceptionInfo expInfo =  ExceptionUtil.getExceptionInfo(this);    	
		return expInfo.getForwardURL();
	}

    
}